package com.xca.znb.view;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.xca.znb.R;
import com.xca.znb.entity.Goods;
import com.xca.znb.entity.Local;
import com.xca.znb.entity.Order;
import com.xca.znb.entity.User;
import com.xca.znb.model.impl.OrderMessageImpl;
import com.xca.znb.presenter.OrderMessagePresenter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class OrderMessage extends AppCompatActivity {
    private TextView userLocal , userName , userPhone , salesName ,goodsName,
    goodsPrice , goodsUnit , goodsNum , needLittle , goodsFreight , orderRemark , totalPay , orderType;
    private ImageView salesImg , goodsImg ;
    private RelativeLayout askSales ;
    private Button refundBtn , receiveBtn ;
    private OrderMessagePresenter presenter ;
    private ImageButton backBtn ;
    private LinearLayout bottomView ;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order_message);
        initView();
        OrderMessageImpl orderMessageImpl = new OrderMessageImpl(this);
        presenter = new OrderMessagePresenter(orderMessageImpl);

        showMessage();

        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    private void showMessage(){
        SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
        String login_phone = sharedPreferences.getString("phone" , "");

        LocalDateTime nowTime = LocalDateTime.now();
        String secTime = nowTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String dayTime = nowTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        Intent intent = getIntent() ;
        int oType = intent.getIntExtra("order_to_msg_type" , 1);
        int orderId = intent.getIntExtra("order_to_message_orderId" , 0);
        Order order = presenter.getOrderById(orderId);
        Goods goods = presenter.getGoodsById(order.getGoodsId());
        Local local = presenter.getLocalById(order.getLocalId());
        User sales = presenter.getUserByPhone(goods.getPublisher());

        userLocal.setText(local.getAddress());
        userName.setText(local.getName());
        userPhone.setText(local.getPhone());

        Glide.with(OrderMessage.this)
                        .load(sales.getConcern())
                                .into(salesImg);
        salesName.setText(sales.getName());

        Glide.with(OrderMessage.this)
                        .load(goods.getFirst_image())
                                .into(goodsImg);
        goodsName.setText(goods.getName());
        double price = goods.getPrice();
        goodsPrice.setText(String.valueOf(price));
        goodsUnit.setText(goods.getUnit());

        int num = order.getNum();
        goodsNum.setText(String.valueOf(num));

        needLittle.setText(String.valueOf(price*num));
        totalPay.setText(String.valueOf(price*num));

        goodsFreight.setText(goods.getFreight());
        orderRemark.setText(order.getRemark());
        orderType.setText(order.getType());

        askSales.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                presenter.addNewsletter(login_phone,goods.getPublisher(),secTime);
                Intent intent1 = new Intent(OrderMessage.this , MessageActivity.class) ;
                intent1.putExtra("goods_send" , login_phone);
                intent1.putExtra("goods_receive" , goods.getPublisher());
                startActivity(intent1);
            }
        });

        if (oType == 1){
            if (order.getType().equals("待发货")){
                receiveBtn.setVisibility(View.GONE);
                refundBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new AlertDialog.Builder(OrderMessage.this)
                                .setMessage("确定退款吗")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        presenter.updateOrderType(order.getId() , "已退款",secTime);
                                        Order order1 = presenter.getOrderById(order.getId());
                                        if (order1.getType().equals("已退款")){
                                            presenter.insertAccount(login_phone , goods.getPrice() * order.getNum() , "退款",dayTime,secTime);
                                            presenter.insertAccount(order.getSales() , goods.getPrice() * order.getNum() , "买家退款",dayTime,secTime);
                                            Toast.makeText(OrderMessage.this, "退款成功", Toast.LENGTH_SHORT).show();
                                            orderType.setText("已退款");

                                        }else {
                                            Toast.makeText(OrderMessage.this, "退款失败", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                })
                                .setNegativeButton("取消", null)
                                .create().show();
                    }
                });
            } else if (order.getType().equals("待收货")) {
                receiveBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new AlertDialog.Builder(OrderMessage.this)
                                .setMessage("确定收货吗")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        presenter.updateOrderType(order.getId() , "已完成",secTime);
                                        Order order1 = presenter.getOrderById(order.getId());
                                        if (order1.getType().equals("已完成")){
                                            Toast.makeText(OrderMessage.this, "收货完成", Toast.LENGTH_SHORT).show();
                                            orderType.setText("已完成");
                                        }else {
                                            Toast.makeText(OrderMessage.this, "收货失败", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                })
                                .setNegativeButton("取消", null)
                                .create().show();
                    }
                });
                refundBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new AlertDialog.Builder(OrderMessage.this)
                                .setMessage("确定退款吗")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        presenter.updateOrderType(order.getId() , "已退款",secTime);
                                        Order order1 = presenter.getOrderById(order.getId());
                                        if (order1.getType().equals("已退款")){
                                            presenter.insertAccount(login_phone , goods.getPrice() * order.getNum() , "退款",dayTime,secTime);
                                            presenter.insertAccount(order.getSales() , goods.getPrice() * order.getNum() , "买家退款",dayTime,secTime);
                                            Toast.makeText(OrderMessage.this, "退款成功", Toast.LENGTH_SHORT).show();
                                            orderType.setText("已退款");

                                        }else {
                                            Toast.makeText(OrderMessage.this, "退款失败", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                })
                                .setNegativeButton("取消", null)
                                .create().show();
                    }
                });
            } else if (order.getType().equals("已完成")||order.getType().equals("已退款")) {
                refundBtn.setVisibility(View.GONE);
                receiveBtn.setVisibility(View.GONE);
                bottomView.setVisibility(View.GONE);
            }
        } else if (oType==2) {
            if (order.getType().equals("待发货")){
                receiveBtn.setText("发货");
                receiveBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new AlertDialog.Builder(OrderMessage.this)
                                .setMessage("确定发货吗")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        presenter.updateOrderType(order.getId() , "待收货",secTime);
                                        Order order1 = presenter.getOrderById(order.getId());
                                        if (order1.getType().equals("待收货")){
                                            Toast.makeText(OrderMessage.this, "发货完成", Toast.LENGTH_SHORT).show();
                                            orderType.setText("待收货");
                                        }else {
                                            Toast.makeText(OrderMessage.this, "发货失败", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                })
                                .setNegativeButton("取消", null)
                                .create().show();
                    }
                });
                refundBtn.setVisibility(View.GONE);
                askSales.setVisibility(View.GONE);
            } else if (order.getType().equals("待收货")||order.getType().equals("已完成")||order.getType().equals("已退款")) {
                refundBtn.setVisibility(View.GONE);
                receiveBtn.setVisibility(View.GONE);
                bottomView.setVisibility(View.GONE);
                askSales.setVisibility(View.GONE);
            }
        }
    }

    @SuppressLint("WrongViewCast")
    private void initView(){
        backBtn = findViewById(R.id.order_message_back);
        userLocal = findViewById(R.id.order_message_local);
        userName = findViewById(R.id.order_message_user_name);
        userPhone = findViewById(R.id.order_message_user_id);
        salesName = findViewById(R.id.order_message_store_name);
        goodsName = findViewById(R.id.order_message_goods_name);
        goodsPrice = findViewById(R.id.order_message_goods_price);
        goodsUnit = findViewById(R.id.order_message_goods_unit) ;
        goodsNum = findViewById(R.id.order_message_number);
        needLittle = findViewById(R.id.order_message_need);
        goodsFreight = findViewById(R.id.order_message_freight);
        orderRemark = findViewById(R.id.order_message_remark);
        totalPay = findViewById(R.id.order_message_total);
        salesImg = findViewById(R.id.order_message_sales_img);
        goodsImg = findViewById(R.id.order_message_goods_img);
        askSales = findViewById(R.id.order_message_ask);
        orderType = findViewById(R.id.order_message_orderType);
        refundBtn = findViewById(R.id.order_message_refund);
        receiveBtn = findViewById(R.id.order_message_receive);
        bottomView = findViewById(R.id.order_message_bottom);
    }

    @Override
    protected void onResume() {
        super.onResume();
        showMessage();
    }
}
